package rabbitMQ.rpc;

import com.rabbitmq.client.*;
import rabbitMQ.constant.Constants;

import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeoutException;

public class RPCClient {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        //创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();

        //设置参数
        factory.setHost("124.223.31.81");
        factory.setPort(5672);
        factory.setVirtualHost("bite");
        factory.setUsername("study");
        factory.setPassword("study");

        //创建连接Connection
        Connection connection = factory.newConnection();

        Channel channel = connection.createChannel();

        channel.queueDeclare(Constants.RPC_REQUEST_QUEUE_NAME, true, false, false, null);
        channel.queueDeclare(Constants.RPC_RESPONSE_QUEUE_NAME, true, false, false, null);

        //设置唯一id
        String correlationID = UUID.randomUUID().toString();
        //设置请求的相关属性
        AMQP.BasicProperties props = new AMQP.BasicProperties().builder()
                .correlationId(correlationID)
                .replyTo(Constants.RPC_RESPONSE_QUEUE_NAME)
                .build();

        String msg = "hello rpc...";
        channel.basicPublish("", Constants.RPC_REQUEST_QUEUE_NAME, props, msg.getBytes());

        //接收响应
        final BlockingQueue<String> response = new ArrayBlockingQueue<>(1);
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String respMsg = new String(body);
                System.out.println("接收到回调消息：" + respMsg);
                if (correlationID.equals(properties.getCorrelationId())) {
                    response.offer(respMsg);
                }
            }
        };
        channel.basicConsume(Constants.RPC_RESPONSE_QUEUE_NAME, true, consumer);
        String result = response.take();
        System.out.println("RPC Client 响应结果" + result);

        //释放资源
      channel.close();
      connection.close();

    }
}
